﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Jzy.Core.Dict;
using ECommerce.Common;
using Jzy.Core.Common;

using Jzy.Core.Common.Web;
using Jzy.Core.Common.Basic;
using ECommerce.Model.Product;
using ECommerce.BLL.Product;
using System.Web.UI.HtmlControls;
using ECommerce.BLL.Advertisement;
using ECommerce.Model.Advertisement;

namespace ECommerce.Web.Site
{
    public partial class ProductList : System.Web.UI.Page
    {
        private string Type1
        {
            get
            {
                return Request.QueryString["Type1"];
            }
        }
        private string Type2
        {
            get
            {
                return Request.QueryString["Type2"];
            }
        }
        private string Type3
        {
            get
            {
                return Request.QueryString["Type3"];
            }
        }
        private string Type4
        {
            get
            {
                return Request.QueryString["Type4"];
            }
        }
        private string Type5
        {
            get
            {
                return Request.QueryString["Type5"];
            }
        }

        private string Type6
        {
            get
            {
                return Request.QueryString["Type6"];
            }
        }

        private int PageIndex
        {
            get
            {
                int pageIndex = 1;
                if(!string.IsNullOrEmpty(Request.QueryString["PageIndex"]))
                {
                    pageIndex = int.Parse(Request.QueryString["PageIndex"]);
                }
                return pageIndex;
            }
        }

        private string ProductName
        {
            get
            {
                return Request.QueryString["ProductName"];
            }
        }

        /// <summary>
        /// direction以_号分隔
        /// </summary>
        private string OrderBy
        {
            get
            {
                string orderBy = "InputTime_desc";
                if (!string.IsNullOrEmpty(Request.QueryString["OrderBy"]))
                {
                    orderBy = Request.QueryString["OrderBy"];
                }
                return orderBy;
            }
        }


        private ECProductBO Product
        {
            get
            {
                return ECProductBO.Instance<ECProductBO>();
            }
        }

        protected string GetScore(object score)
        {
            int avgScore = (int)Math.Round((double)score);
            string star = "";
            for (int i = 0; i < avgScore; i++)
            {
                star += "<img src='images/tbg1.jpg' />";
            }
            return star;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindType();
                BindView();
                DispAdvertisement();
            }
        }

        private void DispAdvertisement()
        {
            AdvertisementBO ad = new AdvertisementBO();
            List<AdvertisementInfo> list = ad.GetList();
            IEnumerable<AdvertisementInfo> tmp = list.Where(T => T.Name == "sub1");
            if (tmp.Count() > 0)
            {
                lnkSub1.HRef = tmp.First().Href;
                imgSub1.Src = tmp.First().BigImageAbsPath;
            }

            tmp = list.Where(T => T.Name == "sub2");
            if (tmp.Count() > 0)
            {
                lnkSub2.HRef = tmp.First().Href;
                imgSub2.Src = tmp.First().BigImageAbsPath;
            }
            
        }

        private void BindType()
        {
            DictBO dict = new DictBO();
            Repeater[] rptTypes = new Repeater[] { rptType1, rptType2, rptType3, rptType4, rptType5, rptType6 };
            int[] items = new int[] { (int)DictItem.品牌分类, (int)DictItem.用途分类, (int)DictItem.材料分类, (int)DictItem.对象分类, (int)DictItem.造型分类, (int)DictItem.价格分类 };
            for (int i = 0; i < rptTypes.Length; i++)
            {
                List<DictInfo> list = dict.GetList(items[i]).ToList();
                DictInfo all = new DictInfo() { Code = 0, Name = "全部" };
                list.Insert(0, all);
                rptTypes[i].DataSource = list;
                rptTypes[i].DataBind();
            }
        }

        private string GetUrl(params int[] excludes) 
        {
            string url = GlobalVar.WebCurrPath + "ProductList.aspx";
            string[] types = new string[] { this.Type1, this.Type2, this.Type3, this.Type4, this.Type5 ,this.Type6};
            for (int i = 1; i < types.Length; i++)
            {
                if (!excludes.Contains(i))
                {
                    url = CombinePara(url, "Type" + i, types[i - 1]);
                }
            }            
            return url;
        }

        private string CombinePara(string url,string key,string value)
        {
            if(!string.IsNullOrEmpty(value))
            {
                if (url.Contains("?"))
                {
                    url += "&" + key + "=" + value;
                }
                else
                {
                    url += "?" + key + "=" + value;
                }

            }
            return url;
        }

        private void BindView()
        {
            PagerSetting setting = new PagerSetting();
            setting.PageIndex = this.PageIndex;
            setting.PageSize = Jzy.Common.AppConfig.PageSize;
            setting.OrderBy = this.OrderBy.Replace("_", " ");
            setting.Where = "State = " + (int)ProductState.上架 + " ";
            CombineWhere(setting, "Type1", this.Type1, "@p0");
            CombineWhere(setting, "Type2", this.Type2, "@p1");
            CombineWhere(setting, "Type3", this.Type3, "@p2");
            CombineWhere(setting, "Type4", this.Type4, "@p3");
            CombineWhere(setting, "Type5", this.Type5, "@p4");
            if (!string.IsNullOrEmpty(this.Type6))
            {
                DictBO dict = new DictBO();
                DictInfo dictInfo = dict.GetList((int)DictItem.价格分类).Where(T => T.Code == int.Parse(this.Type6)).First();

                string lowPrice = dictInfo.Name.Split('-')[0];
                string highPrice = dictInfo.Name.Split('-')[1];
                setting.Where += " and CurrentPrice between " + lowPrice + " and " + highPrice;
            }


            if (!string.IsNullOrEmpty(ProductName))
            {
                setting.Where = "Name like @p5 or Material like @p5";
            }

            List<ECProductInfo> list = Product.GetList(setting, Type1, Type2, Type3, Type4, Type5, "%" + ProductName + "%");
            rptProduct.DataSource = list;
            rptProduct.DataBind();

            string prefix = GetUrl();
            litPager.Text = HtmlPager.Render(setting, prefix, true);

            string sortExpression = this.OrderBy.Split('_')[0].ToLower();
            string sortDirection = this.OrderBy.Split('_')[1].ToLower();

            if (prefix.Contains("?"))
            {
                prefix += "&";
            }
            else
            {
                prefix += "?";
            }

            lnkDefault.NavigateUrl = prefix + "OrderBy=InputTime_desc";

            if (sortExpression == "salesvolume")
            {
                lnkPrice.NavigateUrl = prefix + "OrderBy=CurrentPrice_asc";
                lnkPrice.CssClass = "two";
                if (sortDirection == "desc")
                {                   
                    lnkSalesVolume.NavigateUrl = prefix + "OrderBy=SalesVolume_asc";
                    lnkSalesVolume.CssClass = "three";
                }
                else
                {                    
                    lnkSalesVolume.NavigateUrl = prefix + "OrderBy=SalesVolume_desc";
                    lnkSalesVolume.CssClass = "five";
                }
            }
            else if (sortExpression == "currentprice")
            {
                lnkSalesVolume.NavigateUrl = prefix + "OrderBy=SalesVolume_asc";
                lnkSalesVolume.CssClass = "two";
                if (sortDirection == "desc")
                {
                    lnkPrice.NavigateUrl = prefix + "OrderBy=CurrentPrice_asc";
                    lnkPrice.CssClass = "three";
                }
                else
                {
                    lnkPrice.NavigateUrl = prefix + "OrderBy=CurrentPrice_desc";
                    lnkPrice.CssClass = "five";
                }
            }
            else
            {
                lnkPrice.NavigateUrl = prefix + "OrderBy=CurrentPrice_asc";
                lnkPrice.CssClass = "two";

                lnkSalesVolume.NavigateUrl = prefix + "OrderBy=SalesVolume_asc";
                lnkSalesVolume.CssClass = "two";
            }

        }

        private void CombineWhere(PagerSetting setting,string key,string value,string para)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (string.IsNullOrEmpty(setting.Where))
                {
                    setting.Where = key + "=" + para;
                }
                else
                {
                    setting.Where += " and " + key + "=" + para;
                }
            }
        }

        protected void rptType1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            SetUrl(e, 1);

        }

        protected void rptType2_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            SetUrl(e, 2);
        }

        protected void rptType3_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            SetUrl(e, 3);
        }

        protected void rptType4_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            SetUrl(e, 4);
        }

        protected void rptType5_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            SetUrl(e, 5);
        }

        protected void rptType6_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            SetUrl(e, 6);
        }

        private void SetUrl(RepeaterItemEventArgs e, int index)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DictInfo info = e.Item.DataItem as DictInfo;
                HtmlAnchor lnkType = (HtmlAnchor)e.Item.FindControl("lnkType");

                string[] types = new string[] { this.Type1, this.Type2, this.Type3, this.Type4, this.Type5, this.Type6 };

                string url = GetUrl(index);
                if (info.Code != 0)//如果是“全部”就不要加参数了
                {
                    if (url.Contains("?"))
                    {
                        url += "&Type" + index + "=" + info.Code;
                    }
                    else
                    {
                        url += "?Type" + index + "=" + info.Code;
                    }
                }

                lnkType.HRef = url;
                lnkType.Attributes["class"] = null;

                //前两部分的组合表示选中“全部”
                if (string.IsNullOrEmpty(types[index - 1]) && info.Code == 0 || info.Code.ToString() == types[index - 1])
                {
                    lnkType.HRef = "javascript:;";
                    lnkType.Attributes["class"] = "all";
                }

            }

        }
    }
}